import pymysql


def connect():
    print('connect to mysql server...')
    db = pymysql.connect("119.23.236.73", "web_ad", "web_ad_#ad_11", "web_ad",charset='utf8')
    print('connect success')
    return db


def insert(db, sql, data = None):
    cursor = db.cursor()  # obtain the cursor
    if data is None:
        try:
            # execute sql
            cursor.execute(sql)
            # commit
            db.commit()
        except:
            # Rollback in case there is any error
            print('插入数据失败!' + sql)
            db.rollback()
    else:
        try:
            cursor.executemany(sql,data)
            db.commit()
        except:
            # Rollback in case there is any error
            print('插入数据失败!' + sql)
            db.rollback()

def close(db):
    db.close()


def querydb(db, sql):
    cursor = db.cursor()
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        return results
    except:
        print("Error: unable to fecth data")


def deletedb(db, sql):
    cursor = db.cursor()
    try:
        cursor.execute(sql)
        db.commit()
    except:
        print('删除数据失败!')
        db.rollback()


def updatedb(db, sql):
    cursor = db.cursor()
    try:
        cursor.execute(sql)
        db.commit()
    except:
        print('更新数据失败!')
        db.rollback()
